package cn.siat.gene.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.siat.common.core.constant.SecurityConstants;
import cn.siat.common.core.domain.R;
import cn.siat.common.core.exception.ServiceException;
import cn.siat.common.core.utils.StringUtils;
import cn.siat.common.core.web.domain.AjaxResult;
import cn.siat.common.redis.service.RedisService;
import cn.siat.common.security.utils.SecurityUtils;
import cn.siat.gene.domain.DesignTBExternalPaccout;
import cn.siat.gene.domain.vo.DesignTBExternalPaccoutVo;
import cn.siat.gene.mapper.DesignTBExternalPaccoutMapper;
import cn.siat.gene.service.ComponentService;
import cn.siat.gene.service.DesignService;
import cn.siat.gene.service.DesignTBExternalPaccoutService;
import cn.siat.gene.service.GenePoolService;
import cn.siat.system.api.RemoteUserService;
import cn.siat.system.api.domain.SysUser;
import cn.siat.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yangmw
 * @create 2022-11-21 15:05
 */
@Service
public class DesignTBExternalPaccoutServiceImpl extends ServiceImpl<DesignTBExternalPaccoutMapper, DesignTBExternalPaccout> implements DesignTBExternalPaccoutService {
    @Autowired
    private DesignTBExternalPaccoutMapper designTBExternalPaccoutMapper;
    @Autowired
    private ComponentService componentService;
    @Autowired
    private DesignService designService;
    @Autowired
    private GenePoolService genePoolService;
    @Autowired
    private RedisService redisService;

    @Override
    public List<DesignTBExternalPaccoutVo> selectDesignTBExternalPaccoutList(DesignTBExternalPaccout designTBExternalPaccout) {
        String userId = SecurityUtils.getUserId();
        designTBExternalPaccout.setUserId(userId);
        return designTBExternalPaccoutMapper.selectExternalPaccoutList(designTBExternalPaccout);
    }

    @Override
    public int insertDesignTBExternalPaccout(DesignTBExternalPaccout designTBExternalPaccout) {
        designTBExternalPaccout.setIsBind(1).setIsDelete(1).setUserId(SecurityUtils.getUserId()).setBindTime(new Date());
        //TODO
        //没非空校验，没校验账号密码，没插入系统编码和接口地址
        return designTBExternalPaccoutMapper.insert(designTBExternalPaccout);
    }

    @Override
    public int unBindDesignTBExternalPaccout(String id) {
        UpdateWrapper<DesignTBExternalPaccout> updateWrapper = new UpdateWrapper<>();
        Date date = null;
        updateWrapper.eq("id",id).set("is_bind",0).set("bind_time",date);
        return designTBExternalPaccoutMapper.update(null,updateWrapper);
    }
    @Override
    public int bindDesignTBExternalPaccout(String id) {
        UpdateWrapper<DesignTBExternalPaccout> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id).set("is_bind",1).set("bind_time",new Date());
        return designTBExternalPaccoutMapper.update(null,updateWrapper);
    }

    @Override
    public int removeExternalPaccout(String id) {
        DesignTBExternalPaccout designTBExternalPaccout = designTBExternalPaccoutMapper.selectById(id);
        if(designTBExternalPaccout == null || 0 == designTBExternalPaccout.getIsDelete()){
            throw new ServiceException("删除关联账户不存在！");
        }
        return designTBExternalPaccoutMapper.deleteById(id);
    }

    @Override
    public int updateExternalPaccout(DesignTBExternalPaccout designTBExternalPaccout) {
        return designTBExternalPaccoutMapper.updateById(designTBExternalPaccout);
    }

    private Boolean hasBind(String system){
        QueryWrapper<DesignTBExternalPaccout> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_bind", 1)
                .eq("is_delete", 1)
                .eq("user_id", SecurityUtils.getUserId())
                .eq("external_system_name", system);
        DesignTBExternalPaccout designTBExternalPaccout = designTBExternalPaccoutMapper.selectOne(queryWrapper);
        return !(designTBExternalPaccout==null);
    }

    @Override
    public Boolean hasBindComponent() {
        return hasBind("元件库系统");
    }

    @Override
    public Boolean hasBindDesign() {
        return hasBind("装置设计系统");
    }

    @Override
    public Boolean hasBindGenePool() {
        return hasBind("基础数据库系统");
    }


    /**
     * 关联系统账号验证
     * @param username
     * @param password
     * @param system
     * @return
     */
    @Override
    public AjaxResult verifyToken(String username, String password, String system) {
        AjaxResult success = null;
        if("元件库系统".equals(system)){
            JSONObject jsonObject = componentService.verifyToken(username, password);
            String msg = jsonObject.toJSONString();
            Object data = jsonObject.get("data");
            if(jsonObject.getBoolean("success")){
                success = new AjaxResult(200,jsonObject.getString("message"),data);
            }else{
                success = new AjaxResult(500,"账号或密码错误",null);
            }

        }else if("装置设计系统".equals(system)){
            R<Map> result = designService.designLogin(username,password);
            success = new AjaxResult(result.getCode(),result.getMsg(),result.getData());
        }else if("基础数据库系统".equals(system)){

            JSONObject jsonObject = genePoolService.login(username, password);
            if(jsonObject.getBoolean("success")){
                success = new AjaxResult(200,jsonObject.getString("msg"),jsonObject.get("data"));
            }else{
                System.err.println(jsonObject);
                success = new AjaxResult(500,jsonObject.getString("msg"),null);
            }
        }else{
            throw new ServiceException("该系统不存在!");
        }
        return success;
    }


}
